﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WLYT.Admin.WebApi.Models;
using WLYT.Application.Interfaces;
using WLYT.Common;
using WLYT.Domain.Model;

namespace WLYT.Admin.WebApi.Controllers
{
    public class AuthController : ApiController
    {
        private readonly IUserService UserService;

        public AuthController(IUserService userService)
        {
            UserService = userService;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request">{name:账号,password:密码}</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<LoginResult> Login([FromBody]LoginRequest request)
        {
            LoginResult rs = new LoginResult();
            Data data = new Data();
            User user = await UserService.GetModelAsync(request.Name, request.Password);
            if (user != null)
            {
                try
                {
                    data.token = JwtHelper.GenerateToken(request.Name);
                    data.user = user;
                    data.expireAt = DateTime.Now.AddMinutes(120);
                    rs.Message = "登陆成功";
                    rs.Success = true;
                    rs.data = data;
                }
                catch (Exception ex)
                {
                    rs.Message = ex.Message;
                    rs.Success = false;
                }
            }
            else
            {
                rs.Message = "账户或密码错误";
                rs.Success = false;
            }
            return rs;
        }
    }
}
